package com.peng.leetcode.array;

/**
 * NumSubmatrixSumTarget
 * <p>
 * 1074. 元素和为目标值的子矩阵数量
 *
 * @author: lupeng6
 * @create: 2021/1/29 20:54
 */
public class NumSubmatrixSumTarget {

    public static void main(String[] args) {
        int[][] matrix = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}};
        int target = 0;
        System.out.println(new NumSubmatrixSumTarget().numSubmatrixSumTarget(matrix, target));
    }

    private int rows;

    private int cols;

    private int target;

    private int[][] matrix;

    private int total = 0;

    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        this.rows = matrix.length;
        this.cols = matrix[0].length;
        this.target = target;
        this.matrix = matrix;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                compute(i, j);
            }
        }

        return total;
    }

    private void compute(int x, int y) {
        for (int rowOffset = 0; rowOffset < rows - x; rowOffset++) {
            for (int colOffset = 0; colOffset < cols - y; colOffset++) {
                if (isEquals(x, y, rowOffset, colOffset)) {
                    total++;
                }
            }
        }
    }

    private boolean isEquals(int x, int y, int rowOffset, int colOffset) {
        int sum = 0;
        for (int i = 0; i <= rowOffset; i++) {
            for (int j = 0; j <= colOffset; j++) {
                sum += matrix[x + i][y + j];
            }
        }
        return sum == target;
    }

}
